package cn.tedu.rabbitmq.demo.consumer;

import cn.tedu.rabbitmq.demo.config.DlxDeclareConfig;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.Date;

@Slf4j
@Component
public class DemoConsumer {
    // 监听 demo-queue 消费消息内容 String
    // 底层 从connection 连接 拿到一个channel
    // channel 调用 basicConsume deliver的handle 包装一个现在bean对象
    // handle方法重点是将消息内容做反序列化处理 而且可以根据自定义消费方法入参形式 传递可以提供数据
    @RabbitListener(queues = "demo-queue")
    public void consumer01(String message) {
        log.info("消费者01收到消息：{}", message);
    }
    @RabbitListener(queues = "demo-queue01")
    public void consumer02(Message message) {
        // 1.拿到消息头 消息属性
        String headerValue = message.getMessageProperties().getHeader("myHeader");
        log.info("消费者02接收到消息头名称：{},值:{}","myHeader",headerValue);
        // 2.手动处理反序列化
        byte[] body = message.getBody();
        String msgStr = new String(body);
        log.info("消费者02接收到消息：{}",msgStr);
    }
    /*@RabbitListener(queues = "demo-queue")
    public void consumer03(Channel channel){
        // 接收底层channel的唯一目的 手动确认 手动拒绝 前提要关闭自动确认 否则确认会冲突
        System.out.println("消费者消费执行");
    }*/
    @RabbitListener(queues = "demo-queue02",ackMode = "MANUAL")
    public void consumer04(String msg,Message message,Channel channel){
        log.info("消费者04接收到消息：{}",msg);
        String headerValue = message.getMessageProperties().getHeader("myHeader");
        log.info("消费者04接收到消息头名称：{},值:{}","myHeader",headerValue);
        try{
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }catch (Exception e){
            log.error("消息确认失败");
        }
    }
    @RabbitListener(queues = {DlxDeclareConfig.DLX_QUEUE_NAME})
    public void consumer05(String msg){
        log.info("消费者05接收到消息：{},消费时间:{}",msg,new Date());
    }
}
